﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Domain.ActiveDirectory.Model
{
    public class Group : IActiveDirectoryObject
    {
        public string Name { get; set; }
        public IEnumerable<string> MemberNames { get; set; }

        public string DistinguishedName { get; set; }

        public override bool Equals(object obj)
        {
            bool isEqual = false;
            if (obj != null)
            {
                Group other = obj as Group;
                isEqual = (this.Name == other.Name)
                    && (hasEqualMembers(this.MemberNames, other.MemberNames));
            }
            return isEqual;
        }

        private bool hasEqualMembers(IEnumerable<string> a, IEnumerable<string> b)
        {
            bool hasEqualMembers = true;
            for (int i = 0; i < a.Count(); i++)
            {
                if (!a.Contains(b.ElementAt(i)))
                {
                    hasEqualMembers = false;
                }
            }
            return hasEqualMembers;
        }

        public override int GetHashCode()
        {
            int hash = 13;
            hash = (hash * 7) + Name.GetHashCode();
            hash = (hash * 7) + MemberNames.GetHashCode();
            return hash;
        }

        public override string ToString()
        {
            StringBuilder stringRepresentation = new StringBuilder();
            stringRepresentation.Append("Group Name: ");
            stringRepresentation.AppendLine(Name);
            stringRepresentation.Append("Member Names: ");
            foreach (string groupName in MemberNames)
            {
                stringRepresentation.Append(groupName);
                if (groupName != MemberNames.Last())
                    stringRepresentation.Append(", ");
            }
            return stringRepresentation.ToString();
        }
    }
}
